package com.frank.demo.nio.netty.http;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.extern.slf4j.Slf4j;

/**
 * Http Server Handler
 *
 * @author biezhi
 *         2017/5/31
 * @author frank
 * @since 2018/04/28
 */
@Slf4j
@ChannelHandler.Sharable
public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) {
        new RequestExecution(ctx, fullHttpRequest.copy()).run();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        if (ctx.channel().isOpen() && ctx.channel().isActive() && ctx.channel().isWritable()) {
            ctx.flush();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        if (null != exceptionHandler) {
//            exceptionHandler.handle((Exception) cause);
//        } else {
//            log.error("Blade Invoke Error", cause);
//        }
//        if (ctx.channel().isOpen() && ctx.channel().isActive() && ctx.channel().isWritable()) {
//            ctx.close();
//        }
        super.exceptionCaught(ctx, cause);
    }

}